import { SubjectComponent } from "../../../../core/subject";
import { GetEditorAttrListByTarget } from "../../bullet_editor_attribute";
import { WorldData } from "../../world_data";
import BulletAttrItem from "../editor/bullet_attr_item";

const { ccclass, property } = cc._decorator;

@ccclass
export default class WorldConfigPanel extends SubjectComponent {
    config: WorldData = null;
    @property(cc.Node)
    attrContain: cc.Node = null;

    @property(cc.Prefab)
    attrItemVec2Prefab: cc.Prefab = null;
    @property(cc.Prefab)
    attrItemBooleanPrefab: cc.Prefab = null;
    @property(cc.Prefab)
    attrItemPrefab: cc.Prefab = null;

    setData(config: WorldData) {
        this.config = config;
        this.refresh();
    }

    refresh() {
        this.attrContain.destroyAllChildren();

        let eac = GetEditorAttrListByTarget(this.config);

        if (!eac) {
            return;
        }

        for (let i = 0; i < eac.items.length; i++) {
            let eaItem = eac.items[i];
            let key = eaItem.property;

            let val = this.config[key];
            let itemNode: cc.Node = null;
            switch (true) {
                case val instanceof cc.Vec2:
                    itemNode = cc.instantiate(this.attrItemVec2Prefab);
                    break;
                case typeof val === "boolean":
                    itemNode = cc.instantiate(this.attrItemBooleanPrefab);
                    break;
                default:
                    itemNode = cc.instantiate(this.attrItemPrefab);
                    break;
            }

            let item = itemNode.getComponent(BulletAttrItem);
            item.setVal(eaItem.name, val);
            this.attrContain.addChild(item.node);
            item.on("edit", (newVal) => {
                switch (true) {
                    case this.config[key] instanceof cc.Vec2:
                        this.config[key] = newVal;
                        break;
                    case typeof val === "boolean":
                        this.config[key] = newVal;
                        break;
                    case typeof this.config[key] == "number":
                        this.config[key] = Number(newVal);
                        break;
                    default:
                        this.config[key] = newVal;
                        break;
                }
            }, this);
        }
    }
}
